import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from datetime import datetime, timedelta
import ccxt
import pandas as pd
import numpy as np
from decimal import Decimal

from config.settings import EXCHANGES, RiskConfig, AnalysisConfig
from backtest.engine import BacktestEngine
from backtest.data import DataHandler
from strategies.ml_enhanced_strategy import MLEnhancedStrategy
from analysis.market_analyzer import MarketAnalyzer
from analysis.chain_analyzer import ChainAnalyzer
from analysis.sentiment_analyzer import SentimentAnalyzer
from analysis.technical_indicators import TechnicalIndicators
from risk.risk_manager import RiskManager
from analysis.ml_predictor import MLPredictor

def run_simulation():
    # 设置回测参数
    start_date = datetime(2024, 1, 1)
    end_date = datetime(2024, 2, 1)
    symbol = 'BTC/USDT'
    timeframe = '1h'
    initial_capital = 100000.0

    # 初始化交易所（使用模拟交易模式）
    exchange = ccxt.okx({
        'apiKey': os.getenv('OKX_API_KEY'),
        'secret': os.getenv('OKX_API_SECRET'),
        'password': os.getenv('OKX_PASSPHRASE'),
        'options': {
            'defaultType': 'spot',
            'test': True  # 启用模拟交易
        },
        'timeout': 30000,  # 增加超时时间到30秒
        'enableRateLimit': True,
        'proxies': {
            'http': 'http://127.0.0.1:7890',  # 如果使用clash
            'https': 'http://127.0.0.1:7890'
        }
    })

    try:
        # 获取历史数据
        print(f"正在获取 {symbol} 的历史数据...")
        
        # 使用离线数据进行回测
        try:
            # 首先尝试从交易所获取实时数据
            ohlcv = exchange.fetch_ohlcv(
                symbol=symbol,
                timeframe=timeframe,
                since=int(start_date.timestamp() * 1000),
                limit=1000
            )
            df = pd.DataFrame(ohlcv, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
            df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
            df.set_index('timestamp', inplace=True)
            
        except Exception as e:
            print(f"无法从交易所获取数据: {str(e)}")
            print("使用示例数据进行回测...")
            
            # 生成示例数据
            periods = 1000
            dates = pd.date_range(start=start_date, periods=periods, freq='H')
            np.random.seed(42)  # 设置随机种子以保证可重复性
            
            # 生成随机价格数据
            base_price = 40000  # BTC基准价格
            volatility = 0.002  # 波动率
            returns = np.random.normal(0, volatility, periods)
            price_multiplier = np.exp(np.cumsum(returns))
            
            df = pd.DataFrame({
                'open': base_price * price_multiplier,
                'close': base_price * price_multiplier * (1 + np.random.normal(0, volatility/2, periods)),
                'high': base_price * price_multiplier * (1 + abs(np.random.normal(0, volatility, periods))),
                'low': base_price * price_multiplier * (1 - abs(np.random.normal(0, volatility, periods))),
                'volume': np.random.lognormal(10, 1, periods)
            }, index=dates)
            
            # 确保high总是最高价，low总是最低价
            df['high'] = df[['open', 'close', 'high']].max(axis=1)
            df['low'] = df[['open', 'close', 'low']].min(axis=1)
        
        print("数据准备完成，开始初始化分析组件...")
        
        # 初始化分析组件
        analysis_config = AnalysisConfig()
        market_analyzer = MarketAnalyzer(config=analysis_config)
        technical_indicators = TechnicalIndicators()
        risk_manager = RiskManager(config=RiskConfig())
        
        # 暂时跳过需要外部API的组件
        # chain_analyzer = ChainAnalyzer(config=analysis_config)
        # sentiment_analyzer = SentimentAnalyzer(config=analysis_config)
        
        # 准备ML模型
        print("准备机器学习模型...")
        features = technical_indicators.calculate_all_indicators(df)
        features['target'] = df['close'].pct_change(24).shift(-24)
        features = features.dropna()
        
        X = features.drop(['target'], axis=1)
        y = (features['target'] > 0).astype(int)
        
        ml_predictor = MLPredictor()
        ml_predictor.train(X, y)
        
        # 创建策略
        print("创建交易策略...")
        strategy = MLEnhancedStrategy(
            market_analyzer=market_analyzer,
            # chain_analyzer=chain_analyzer,
            # sentiment_analyzer=sentiment_analyzer,
            risk_manager=risk_manager,
            ml_predictor=ml_predictor,
            technical_indicators=technical_indicators
        )
        
        # 创建回测引擎
        print("初始化回测引擎...")
        engine = BacktestEngine(
            data_handler=DataHandler(),
            strategy=strategy,
            risk_manager=risk_manager,
            initial_capital=initial_capital
        )
        
        # 运行回测
        print("\n开始回测...")
        engine.run_backtest()
        
        # 获取回测结果
        results = engine.get_backtest_results()
        
        # 打印回测结果
        print("\n=== 回测结果 ===")
        print(f"初始资金: ${initial_capital:,.2f}")
        print(f"最终资金: ${results['Final Capital']:,.2f}")
        print(f"总收益率: {results['Total Return']*100:.2f}%")
        print(f"夏普比率: {results['Sharpe Ratio']:.2f}")
        print(f"最大回撤: {results['Max Drawdown']*100:.2f}%")
        print(f"总手续费: ${results['Total Commission']:,.2f}")
        
        # 保存详细结果到CSV
        results['Positions History'].to_csv('simulation_positions.csv')
        results['Holdings History'].to_csv('simulation_holdings.csv')
        print("\n详细结果已保存到 simulation_positions.csv 和 simulation_holdings.csv")
        
    except Exception as e:
        print(f"模拟交易过程中出错: {str(e)}")
        raise

if __name__ == "__main__":
    run_simulation()
